/*
 * @Author: Njpyy
 * @Date: 2024-03-12 23:54:16
 * @LastEditors: Njpyy
 * @LastEditTime: 2024-03-17 10:07:57
 * @FilePath: /big-event/src/utils/request.js
 * @Description: 
 */
//导入axios  npm install axios
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/store/token';

//下面这种路由导入方式，会报错，模块导入问题
// import { useRouter } from 'vue-router';
// const router = useRouter()

import router from '@/router'

//定义一个变量,记录公共的前缀  ,  baseURL
// const baseURL = 'http://localhost:8080';
const baseURL = '/api';
const instance = axios.create({ baseURL })

//添加请求拦截器
instance.interceptors.request.use(
    //请求前的回调
    config => {
        const tokenStore = useTokenStore()
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token
        }
        return config
    },

    //请求错误的回调
    err => {
        return Promise.reject(err)
    }
)


//添加响应拦截器
instance.interceptors.response.use(
    result => {
        //判断业务状态码
        if (result.data.code === 0) {
            return result.data
        }

        //操作失败
        ElMessage.error(result.data.msg ? result.data.msg : '服务异常')

        //异步操作的状态转换为失败
        return Promise.reject(result.data)
    },
    err => {
        if (err.response.status === 401) {//未授权，直接跳转登录页
            ElMessage.error('请重新登录~')
            router.push('/login')
        } else {
            ElMessage.error('服务异常')
        }
        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;